import React from 'react';
import { routerShape } from 'react-router';
import { inject, observer } from 'mobx-react';
import { Icon, Spin, message, Popover } from 'antd';
import { toJS } from 'mobx';
import isEmpty from 'lodash/isEmpty';
import
  {
    WeaNewScroll,
    WeaTools,
    WeaLeftTree,
    WeaLocaleProvider,
	} from 'ecCom';

const { addLeaf, getDefautDatasShow, doFavEdit } = WeaLeftTree;
const getLabel = WeaLocaleProvider.getLabel;
@inject('docAddStore')

@observer
class AddContent extends React.Component {
	static contextTypes = {
    router: routerShape,
  };
  constructor(props) {
    super(props);
    const datasShow = this.props.docAddStore.treeDatas || [];
    const _datas = addLeaf(datasShow);
    let treeData = getDefautDatasShow(_datas);
    this.state = {
      treeData,
      hasRight: false, // 当前选中的节点是否有创建权限，默认无
    };
  }
  componentDidMount() {
  }
  componentWillReceiveProps(nextProps) {
    const { docAddStore } = this.props;
    const { selectedDomId, treeDatas } = docAddStore;
    if (selectedDomId.toJS().length === 0) {
      this.setState({ treeData: treeDatas.toJS(), hasRight: false });
    } else {
      treeDatas.toJS().forEach((item) => {
        let tempResult = [];
        tempResult = this.getItem(item, selectedDomId.toJS());
        if (tempResult.getNode === true) {
          if (tempResult.item.haschild) {
            this.setState(
              { treeData: tempResult.item.childs,
                hasRight: tempResult.item.hasRight,
              });
          } else {
            this.setState({ treeData: [], hasRight: tempResult.item.hasRight });
          }
        }
      });
    }
  }
  shouldComponentUpdate() {
    return true;
  }
  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
  }
  getItem = (item, selected) => {
    let getNode = false;
    let sel = selected[0] || '';
    if (item.domid === sel) {
      getNode = true;
    } else if (item.haschild) {
        item.childs.forEach((i) => {
          let tempResult = [];
          tempResult = this.getItem(i, selected);
          if (tempResult.getNode) {
            if (tempResult.item.haschild) {
              this.setState(
                { treeData: tempResult.item.childs, hasRight: tempResult.item.hasRight },
              );
            } else {
              this.setState({ treeData: [], hasRight: tempResult.item.hasRight });
            }
          }
        });
      }
    return { item, getNode };
  }
  getItemForLeftTree = (item, selected) => {
    let getNode = false;
    let returnItem = [];
    let sel = selected[0] || '';
    if (item.domid === sel) {
      getNode = true;
      returnItem.push({ item, getNode });
    } else {
      returnItem.push({ item, getNode });
      if (item.haschild) {
        item.childs.forEach((i) => {
          let tempResult = [];
          tempResult = this.getItemForLeftTree(i, selected);
          returnItem = returnItem.concat(tempResult);
        });
      }
    }
    return returnItem;
  }
  getShowItem = (tempResult, domid, pid) => {
    let result = [];
    let temp = [];
    tempResult.forEach((item) => {
      if (item.item.domid === domid) {
        result.unshift(item.item);
      }
    });
    tempResult.forEach((item) => {
      if (item.item.key === pid) {
        result.unshift(item.item);
        temp = [];
        if (pid !== '') {
          temp = this.getShowItem(tempResult, item.item.domid, item.item.pid);
          temp.pop();
          result = temp.concat(result);
        }
      }
    });
    return result;
  }
  getExpandedKey() {
    const { docAddStore } = this.props;
    const { treeDatas, selectedDomId, setExpandedKey } = docAddStore;
    let tempExpandedkey = [];
    let selectedDomID = toJS(selectedDomId);
    if (selectedDomID.length !== 0) {
      treeDatas.forEach((item) => {
        if (item.domid === selectedDomID[0]) {
          tempExpandedkey.push(item.domid);
        } else if (item.haschild) {
            const tempResult = this.getItemForLeftTree(item, selectedDomID);
            tempResult.forEach((iteml) => {
              if (iteml.getNode) {
                const temptreeData = this.getShowItem(tempResult, iteml.item.domid, iteml.item.pid);
                temptreeData.forEach((i) => {
                  tempExpandedkey.push(i.domid);
                });
              }
            });
          }
      });
      setExpandedKey(tempExpandedkey);
    }
  }
  render() {
    const { treeData, hasRight } = this.state;
    const { docAddStore, location } = this.props;
    const { setSelectedDomId, searchValue, setsearchValue, domKey
      , linkRout, linkUrl, openNewWindow, params, key
      , selectedDomId, setKey, isTreeNodeEmpty, setIsTreeNodeEmpty
      , loadingAdd, getTreeDatas, setTreeDatas, treeDatas
      , accounts: { belong_users, canCreate, f_weaver_belongto_userid, f_weaver_belongto_usertype } } = docAddStore;
    const pattern = new RegExp(searchValue, 'i');
    let content = treeData.map((item) => {
      if (pattern.test(item.name) || pattern.test(item.ecologyPinyinSearch)) {
        return (
          <div className="add-addcontent"
            onClick={() => {
            setSelectedDomId(item.domid);
            setKey([item.key]);
            setsearchValue('');
            this.getExpandedKey();
            setIsTreeNodeEmpty(false);
          }}
          >
            <div
              className={`icon-coms-Collection${item.fav ? '2' : ''}`}
              onClick={(e) => {
                WeaTools.callApi('/api/doc/category/collute', 'GET', {
                  operate: item.fav ? 'undo' : 'do',
                  secid: item.key,
                }).then((data) => {
                  if (data.status === 1) {
                    let treeData = doFavEdit(toJS(treeDatas), item.domid);
                    setTreeDatas(treeData);
                    if (item.fav) message.success(data.msg || getLabel(83885, '操作成功！'));
                    else message.success(data.msg || `${getLabel(83885, '操作成功！')}`);
                  } else {
                    message.warning(data.msg || getLabel(384402, '操作失败，请重试！'));
                  }
                });
                e.stopPropagation && e.stopPropagation();
                e.preventDefault && e.preventDefault();
                e.nativeEvent && e.nativeEvent.preventDefault();
            }}
            />
            <div className="add-addcontentsub">
              <img src={'/spa/document/images/file.png'} />
              <div className="add-addkey">{item.domid}</div>
              <div className="add-addtext">{item.name}</div>
            </div>
          </div>
        );
      }
    });
    if (!loadingAdd && content.length === 0 && isTreeNodeEmpty) {
      content = (
        <div className="add-addcontent-empty">
          <div className="icon-coms-blank add-addcontent-blank" />
          <div>{getLabel(83553, '暂无数据')}</div>
        </div>
      );
    }

    const _belong_users = toJS(belong_users);
    const accountCom = (<div>
      <div style={{ color: '#666', fontWeight: 600, padding: '5px 16px' }}>{getLabel(17747, '次账号')}</div>
      <div>
        {
          Array.isArray(_belong_users) && !isEmpty(_belong_users) && _belong_users.map(v => (<div className="text-elli sub-account"
            title={v.f_weaver_belongto_show}
            onClick={() => {
                        const url = `${linkUrl}?${domKey}=${
                           key[0]}${params}&f_weaver_belongto_userid=${v.f_weaver_belongto_userid}&f_weaver_belongto_usertype=${v.f_weaver_belongto_usertype}${linkRout}`;
                        if (openNewWindow === '1') {
                          window.open(url);
                        } else {
                          window.location.href = url;
                        }
              }}
          >{v.f_weaver_belongto_show}</div>))
        }
      </div>
    </div>);
    return (
        <div className="add-addcontentmain">
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@v67vb3`} height={'100%'}>
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@2rw2od`} spinning={loadingAdd}>
                {
                  hasRight && (
                    <div className="add-addcontentplus"
                      onClick={
                      () => {
                        const url = `${linkUrl}?${domKey}=${
                           key[0]}${params}&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=${f_weaver_belongto_usertype}${linkRout}`;
                        if (openNewWindow === '1') {
                          window.open(url);
                        } else {
                          window.location.href = url;
                        }
                      }
                    }
                    >
                      <div className="add-addcontentsub add-addcontentsubplus">
                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@4bk4yq`} type="plus" className=" add-addtabicon-plus" />
                      </div>
                      {
                        canCreate && Array.isArray(_belong_users) && !isEmpty(_belong_users) && <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@8z085f`}
                          getTooltipContainer={() => this.refs.addAccounts}
                          content={accountCom}
                          trigger="click"
                          placement="bottomLeft"
                          overlayClassName="wea-doc-add-popover"
                          overlayStyle={{ width: 152 }}
                        >
                          <span className="icon-coms-Related-account add-accounts"
                            ref="addAccounts"
                            onClick={(e) => {
                              e.stopPropagation && e.stopPropagation();
                              e.preventDefault && e.preventDefault();
                              e.nativeEvent && e.nativeEvent.preventDefault();
                            }}
                          />
                        </Popover>
                      }
                    </div>
                  )
                }
                {content}
              </Spin>
            </WeaNewScroll>
        </div>
    );
  }
}
export default AddContent;
